package com.layer.cms.generate.service.impl;

import com.layer.cms.generate.pojo.TableClass;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

/**
 * 
 * @description: Freemarker 生成代码的实现方式
 * @author 小新
 * @datetime: 2024年4月28日 下午8:48:30
 *
 */
public class FreemarkerGenerateCodeService {

	Configuration cfg = null;

	{
		cfg = new Configuration(Configuration.VERSION_2_3_31);
		cfg.setTemplateLoader(new ClassTemplateLoader(FreemarkerGenerateCodeService.class, "/ftl"));
		cfg.setDefaultEncoding("UTF-8");
	}

	public void generateCode(List<TableClass> list, String path) throws Exception {

		// 获得所有模板
		Template modelTemplate = cfg.getTemplate("Model.java.ftl");
		Template modelDto = cfg.getTemplate("Dto.java.ftl");
		Template modelVo = cfg.getTemplate("Vo.java.ftl");

		Template controller = cfg.getTemplate("Controller.java.ftl");
		Template service = cfg.getTemplate("Service.java.ftl");
		Template serviceImpl = cfg.getTemplate("ServiceImpl.java.ftl");
		Template mapper = cfg.getTemplate("Mapper.java.ftl");
		Template mapping = cfg.getTemplate("Mapping.xml.ftl");

		for (TableClass tab : list) {

			String savePath = path + "/" + tab.getPackageName().replace(".", "/");

			generate(modelTemplate, tab, savePath + "/pojo/");
			generate(modelDto, tab, savePath + "/dto/");
			generate(modelVo, tab, savePath + "/vo/");

			generate(controller, tab, savePath + "/controller/");
			generate(service, tab, savePath + "/service/");
			generate(serviceImpl, tab, savePath + "/service/impl/");
			generate(mapper, tab, savePath + "/mapper/");
			generate(mapping, tab, savePath + "/mapper/mapping");
		}
	}

	/**
	 * 根据变量和模板生成对应的代码
	 * 
	 * @param template   模板
	 * @param tableClass 类信息
	 * @param path       保存地址
	 */
	private void generate(Template template, TableClass tableClass, String path) {

		isFilePathExist(path);

		String fileName = "";
		if (template.getName().equalsIgnoreCase("Model.java.ftl")) {

			fileName = path + "/" + tableClass.getClassName() + ".java";
		} else {
			fileName = path + "/" + tableClass.getClassName() + template.getName().replace(".ftl", "");
		}

		FileOutputStream fos = null;
		OutputStreamWriter out = null;

		try {

			fos = new FileOutputStream(fileName);
			out = new OutputStreamWriter(fos);

			template.process(tableClass, out);

		} catch (IOException | TemplateException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void isFilePathExist(String path) {

		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
	}
}
